package com.caigou.comm.base.ext

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*

/**
 * @author #Suyghur.
 * Created on 2022/02/15
 */

/**
 * 倒计时
 */
fun countDownCoroutines(total: Int, onTick: (Int) -> Unit, onFinish: () -> Unit, scope: CoroutineScope = CoroutineScope(Dispatchers.IO)): Job {
    return flow {
        for (i in total downTo 0) {
            emit(i)
            delay(1000)
        }
    }.flowOn(Dispatchers.Default)
        .onCompletion { onFinish.invoke() }
        .onEach { onTick.invoke(it) }
        .flowOn(Dispatchers.Main)
        .launchIn(scope)
}